package com.darcytech.debezium.server.controller;

import com.darcytech.debezium.core.api.bo.RegisterInfo;
import com.darcytech.debezium.core.api.bo.RegisterResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.darcytech.debezium.common.utils.MD5Utils;
import com.darcytech.debezium.common.utils.ObjectMapperUtils;
import com.darcytech.debezium.server.DebeziumProperties;
import com.darcytech.debezium.server.service.RegisterService;

@RestController
@RequestMapping("connectors")
public class RegisterController {

    private final RegisterService registerService;

    private final DebeziumProperties debeziumProperties;

    public RegisterController(RegisterService registerService, DebeziumProperties debeziumProperties) {
        this.registerService = registerService;
        this.debeziumProperties = debeziumProperties;
    }

    @PostMapping("registerGroup")
    public RegisterResult register(@RequestParam String sign, @RequestBody RegisterInfo registerInfo) {
        String calcSign = MD5Utils.md5(ObjectMapperUtils.writeAsString(registerInfo) + debeziumProperties.getSecret());
        if (!calcSign.equals(sign)) {
            return new RegisterResult(RegisterResult.ERROR_CODE, "sign failed");
        }
        return registerService.register(registerInfo);
    }
}
